package com.myblog.config.security.handle;

import com.myblog.common.ResultInfoFactory;
import com.myblog.config.properties.SecurityProperties;
import com.myblog.emun.ErrorCodeEnum;
import com.myblog.emun.LoginResponseType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class CustomAuhtenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        if (LoginResponseType.JSON.equals(securityProperties.getLoginResponseType())) {
            ResultInfoFactory result = new ResultInfoFactory();
            result.setMessage(ErrorCodeEnum.UNAUTHORIZED.getMessage());
            httpServletResponse.setContentType("application/json;charset=UTF-8");
            httpServletResponse.getWriter().write(result.toJsonString(result));
        } else {
            //super.setDefaultFailureUrl(securityProperties.getLoginPage()+"?error");
            Object toAuthentication = httpServletRequest.getAttribute("toAuthentication");
            //获取上一次请求路径
            String referer = httpServletRequest.getHeader("Referer");
            log.info("referer:{}", referer);
            String lastUrl = toAuthentication != null ? securityProperties.getLoginProcessingUrl() : StringUtils.substringBefore(referer, "?");
            log.info("上次的请求路径为:{}", lastUrl);
            super.setDefaultFailureUrl(lastUrl + "?error");
            super.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
        }
    }
}
